/**
 * VimL内置函数综合示例
 * 
 * 本示例展示了VimL虚拟机中的各种内置函数，包括：
 * 1. 字符串处理函数（len、empty、stridx、strpart、tolower、toupper）
 * 2. 列表操作函数（len、empty、add、remove）
 * 3. 字典操作函数（len、empty、keys、values、has_key）
 * 4. 实际应用场景演示
 * 
 * 这些内置函数是VimL编程的重要工具，掌握它们能极大提高编程效率。
 * 
 * 编译和运行：
 * mkdir -p build && cd build
 * cmake .. && ninja
 * ./bin/builtin_functions_example
 * 
 * 作者：VimL虚拟机项目组
 * 日期：2025-09-27
 */

#include "viml/compiler.h"
#include "viml/vm.h"
#include <iostream>

using namespace viml;

void print_header(const std::string& title) {
    std::cout << "\n" << std::string(60, '=') << std::endl;
    std::cout << " " << title << std::endl;
    std::cout << std::string(60, '=') << std::endl;
}

int main() {
    try {
        Compiler compiler;
        VM vm;
        
        print_header("VimL内置函数综合示例");
        
        // ========== 字符串处理函数 ==========
        std::string string_functions = R"(
echo "=== 字符串处理函数 ==="

" 1. len() - 获取字符串长度
let text = "Hello VimL!"
echo "文本:", text
echo "长度:", len(text)

let chinese_text = "你好世界"
echo "中文文本:", chinese_text
echo "字节长度:", len(chinese_text)

" 2. empty() - 检查字符串是否为空
let empty_str = ""
let non_empty = "content"
echo "空字符串是否为空:", empty(empty_str)
echo "非空字符串是否为空:", empty(non_empty)

" 3. tolower() 和 toupper() - 大小写转换
let mixed_case = "Hello World"
echo "原文本:", mixed_case
echo "转小写:", tolower(mixed_case)
echo "转大写:", toupper(mixed_case)
)";
        
        std::cout << "执行字符串处理函数示例..." << std::endl;
        auto bytecode1 = compiler.compile(string_functions, "string_functions.vim");
        vm.execute(bytecode1);
        
        // ========== 列表操作函数 ==========
        compiler.reset();
        vm.reset();
        
        std::string list_functions = R"(
echo "=== 列表操作函数 ==="

" 1. 创建和检查列表
let numbers = [1, 2, 3, 4, 5]
let empty_list = []

echo "数字列表:", numbers
echo "列表长度:", len(numbers)
echo "空列表长度:", len(empty_list)
echo "列表是否为空:", empty(numbers)
echo "空列表是否为空:", empty(empty_list)

" 2. 列表元素访问
echo "第一个元素:", numbers[0]
echo "最后一个元素:", numbers[len(numbers) - 1]

" 3. 列表操作
let fruits = ["苹果", "香蕉"]
echo "水果列表:", fruits
let fruits = fruits + ["橘子", "葡萄"]
echo "添加后的列表:", fruits
echo "新的长度:", len(fruits)
)";
        
        std::cout << "\n执行列表操作函数示例..." << std::endl;
        auto bytecode2 = compiler.compile(list_functions, "list_functions.vim");
        vm.execute(bytecode2);
        
        // ========== 字典操作函数 ==========
        compiler.reset();
        vm.reset();
        
        std::string dict_functions = R"(
echo "=== 字典操作函数 ==="

" 1. 创建和检查字典
let person = {"name": "张三", "age": 25, "city": "北京"}
let empty_dict = {}

echo "人员信息:", person
echo "字典大小:", len(person)
echo "空字典大小:", len(empty_dict)
echo "字典是否为空:", empty(person)
echo "空字典是否为空:", empty(empty_dict)

" 2. 字典元素访问
echo "姓名:", person["name"]
echo "年龄:", person["age"]
echo "城市:", person["city"]

" 3. 检查键是否存在
echo "包含name键:", has_key(person, "name")
echo "包含phone键:", has_key(person, "phone")

" 4. 获取所有键和值
echo "所有键:", keys(person)
echo "所有值:", values(person)
)";
        
        std::cout << "\n执行字典操作函数示例..." << std::endl;
        auto bytecode3 = compiler.compile(dict_functions, "dict_functions.vim");
        vm.execute(bytecode3);
        
        // ========== 实际应用场景 ==========
        compiler.reset();
        vm.reset();
        
        std::string practical_examples = R"(
echo "=== 实际应用场景 ==="

" 1. 文本处理应用
function process_text(text)
    echo "原始文本:", text
    echo "长度:", len(text)
    
    if empty(text)
        echo "文本为空，无需处理"
        return ""
    endif
    
    " 转换为小写
    let processed = tolower(text)
    echo "处理后:", processed
    
    return processed
endfunction

let sample_text = "Hello World Example"
let result = process_text(sample_text)

" 2. 数据统计应用
function analyze_data(data_list)
    if empty(data_list)
        echo "数据列表为空"
        return {}
    endif
    
    let total = 0
    let count = len(data_list)
    
    for item in data_list
        let total = total + item
    endfor
    
    let average = total / count
    
    let stats = {
        "count": count,
        "total": total,
        "average": average
    }
    
    return stats
endfunction

let test_data = [10, 20, 30, 40, 50]
echo "测试数据:", test_data
let statistics = analyze_data(test_data)
echo "统计结果:", statistics
echo "数据个数:", statistics["count"]
echo "总和:", statistics["total"]
echo "平均值:", statistics["average"]

" 3. 配置管理应用
function validate_config(config)
    let required_keys = ["host", "port", "user"]
    let missing_keys = []
    
    for key in required_keys
        if not has_key(config, key)
            let missing_keys = missing_keys + [key]
        endif
    endfor
    
    if empty(missing_keys)
        echo "配置验证通过"
        return 1
    else
        echo "缺少必需的配置项:", missing_keys
        return 0
    endif
endfunction

let config1 = {"host": "localhost", "port": 8080, "user": "admin"}
let config2 = {"host": "localhost", "port": 8080}

echo "配置1:", config1
let valid1 = validate_config(config1)

echo "配置2:", config2
let valid2 = validate_config(config2)
)";
        
        std::cout << "\n执行实际应用场景示例..." << std::endl;
        auto bytecode4 = compiler.compile(practical_examples, "practical_examples.vim");
        vm.execute(bytecode4);
        
        print_header("内置函数学习总结");
        
        std::cout << "📚 内置函数分类和用途：" << std::endl;
        
        std::cout << "\n1. 字符串处理函数：" << std::endl;
        std::cout << "   • len(str) - 获取字符串长度" << std::endl;
        std::cout << "   • empty(str) - 检查是否为空字符串" << std::endl;
        std::cout << "   • tolower(str) - 转换为小写" << std::endl;
        std::cout << "   • toupper(str) - 转换为大写" << std::endl;
        std::cout << "   📝 适用于文本处理和格式化" << std::endl;
        
        std::cout << "\n2. 列表操作函数：" << std::endl;
        std::cout << "   • len(list) - 获取列表长度" << std::endl;
        std::cout << "   • empty(list) - 检查是否为空列表" << std::endl;
        std::cout << "   • list[index] - 访问列表元素" << std::endl;
        std::cout << "   • list1 + list2 - 列表连接" << std::endl;
        std::cout << "   📝 适用于数组和集合操作" << std::endl;
        
        std::cout << "\n3. 字典操作函数：" << std::endl;
        std::cout << "   • len(dict) - 获取字典大小" << std::endl;
        std::cout << "   • empty(dict) - 检查是否为空字典" << std::endl;
        std::cout << "   • has_key(dict, key) - 检查键是否存在" << std::endl;
        std::cout << "   • keys(dict) - 获取所有键" << std::endl;
        std::cout << "   • values(dict) - 获取所有值" << std::endl;
        std::cout << "   📝 适用于配置管理和数据结构操作" << std::endl;
        
        std::cout << "\n🎯 使用建议：" << std::endl;
        std::cout << "• 充分利用内置函数提高开发效率" << std::endl;
        std::cout << "• 在处理数据前先检查empty()避免错误" << std::endl;
        std::cout << "• 使用len()进行边界检查" << std::endl;
        std::cout << "• 合理使用字典的has_key()进行安全访问" << std::endl;
        
        std::cout << "\n🔍 实际应用场景：" << std::endl;
        std::cout << "• 文本处理和格式化" << std::endl;
        std::cout << "• 数据验证和统计分析" << std::endl;
        std::cout << "• 配置文件管理" << std::endl;
        std::cout << "• 数据结构操作和转换" << std::endl;
        
        std::cout << "\n🎉 内置函数示例演示完成！" << std::endl;
        
        return 0;
        
    } catch (const std::exception& e) {
        std::cout << "\n❌ 内置函数示例执行失败: " << e.what() << std::endl;
        return 1;
    }
}